<template>
  <div>
    <!-- add inference dialog start -->
    <el-dialog
        v-model="addVisible"
        title="添加任务"
        width="30%"
        align-center
    >
      <div>
        <el-tabs type="border-card" class="demo-tabs">
          <!-- tasks start -->
          <el-tab-pane label="任务集推理">
            <div>
              <el-select v-model="taskValue" placeholder="Select">
                <el-option
                    v-for="item in tasks"
                    :key="item.taskName"
                    :label="item.taskName"
                    :value="item.taskId"
                >
                  <span style="float: left">{{ item.taskName }}</span>
                  <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px">
                    {{ item.taskId }}
                  </span>
                </el-option>
              </el-select>
              <el-button color="#409eff" :dark="isDark" plain @click="tasksInference">推理</el-button>
            </div>
          </el-tab-pane>
          <!-- tasks end -->

          <!-- tasksImg start -->
          <el-tab-pane label="任务集内单张推理">
            <div>
              <el-select v-model="tasksImgValue" placeholder="Select" @change="changeSelect">
                <el-option
                    v-for="item in tasksImg"
                    :key="item.taskName"
                    :label="item.taskName"
                    :value="item.taskId"
                >
                  <span style="float: left">{{ item.taskName }}</span>
                  <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px">
                    {{ item.taskId }}
                  </span>
                </el-option>
              </el-select>
              <el-select v-model="ImgValue" placeholder="Select" @change="changeSelect">
                <el-option
                    v-for="item in Imgs"
                    :key="item.imgName"
                    :label="item.imgName"
                    :value="item.imgId"
                >
                  <span style="float: left">{{ item.imgName }}</span>
                  <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px">
                    {{ item.imgId }}
                  </span>
                </el-option>
              </el-select>
            </div>
          </el-tab-pane>
          <!-- tasksImg end -->

          <!-- Img start -->
          <el-tab-pane label="单独推理">
            <div>
              <el-form :model="imgData" status-icon ref="formRef" label-width="80px" class="demo-ruleForm">
                <!-- upload file end -->
                <el-form-item>
                  <input type="file" @change="uploadFiles">
                  <div class="drop_box"  @dragover.prevent @drop="dropFiles">
                    {{ dropFileName }}
                  </div>
                </el-form-item>
                <!-- upload file end -->

                <!-- exSript select start -->
                <el-form-item>
                  <el-select v-model="exScriptsValue" placeholder="Select">
                    <el-option
                        v-for="item in exScripts"
                        :key="item.scriptName"
                        :label="item.scriptName"
                        :value="item.scriptId"
                    >
                      <span style="float: left">{{ item.scriptName }}</span>
                      <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px">
                        {{ item.scriptId }}
                      </span>
                    </el-option>
                  </el-select>
                </el-form-item>
                <!-- exSript select end -->

                <!-- backSript select start -->
                <el-form-item>
                  <el-select v-model="backScriptsValue" placeholder="Select">
                    <el-option
                        v-for="item in backScripts"
                        :key="item.scriptName"
                        :label="item.scriptName"
                        :value="item.scriptId"
                    >
                      <span style="float: left">{{ item.scriptName }}</span>
                      <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px">
                        {{ item.scriptId }}
                      </span>
                    </el-option>
                  </el-select>
                </el-form-item>
                <!-- backSript select end -->

                <!-- model select start -->
                <el-form-item>
                  <el-select v-model="modelsValue" placeholder="Select">
                    <el-option
                        v-for="item in models"
                        :key="item.modelId"
                        :label="item.modelName"
                        :value="item.modelId"
                    >
                      <span style="float: left">{{ item.modelName }}</span>
                      <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px">
                        {{ item.modelId }}
                      </span>
                    </el-option>
                  </el-select>
                </el-form-item>
                <!-- model select end -->

                <el-form-item style="margin: 20px auto auto;">
                  <el-button type="primary" @click="ImgInference">提交</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
          <!-- Img end -->

        </el-tabs>
      </div>
    </el-dialog>
    <!-- inference dialog end -->

    <el-button @click="addView">推理</el-button>
  </div>
</template>

<script>
import {ref} from "vue";
import inference from "@/api/inference"
import quota from "@/api/quota"
import task from "@/api/task"
import {ElMessage} from "element-plus";
import tokenTools from "@/assets/tools/tokenTools";

export default {
  name: "Inference",

  setup() {
    // 推理弹出层控制
    const addVisible = ref(false)

    // 选择模型
    const taskValue = ref('')
    let tasks = ref([])

    const tasksImgValue = ref('')
    let tasksImg = ref([])
    const ImgValue = ref('')
    let Imgs = ref([])

    const exScriptsValue = ref('')
    let exScripts = ref([])
    const backScriptsValue = ref('')
    let backScripts = ref([])
    const modelsValue = ref('')
    let models = ref([])

    // dropFile 提示语
    let dropFileName = ref("或者将文件拖到此区域上传")


    // form数据模型
    const imgData = ref({
      imgName: '',
    })
    const formRef = ref(null)

    // 上传的form数据
    const formData = new FormData();

    // 推理的弹出层
    function addView() {
      addVisible.value = true
      let userId = JSON.parse(localStorage.getItem('userData')).userId
      let da = {}
      da.userId = userId

      exScripts.value.length = 0
      backScripts.value.length = 0
      if(tokenTools.getToken() === null){
        ElMessage.error("请先登录!")
      }else{
        inference.taskList(da).then(res => {
          if (res.code === 200) {
            tasks.value = res.data
            tasksImg.value = res.data

            task.about(da).then(res => {
              res.data.scripts.forEach(function (element) {
                if (element.tag === 0) {
                  exScripts.value.push(element)
                } else {
                  backScripts.value.push(element)
                }
              })
              models.value = res.data.models
            })
          }
        })
      }
    }

    // 获取任务集所用的数据集内图像信息
    function changeSelect() {
      console.log(parseInt(tasksImgValue.value))
      let da = {}
      da.taskId = parseInt(tasksImgValue.value)
      inference.imgsList(da).then(res => {
        if (res.code === 200) {
          console.log(res)
          Imgs.value = res.data.imgs
        }
      })
    }

    // 任务集推理
    function tasksInference() {
      console.log("任务集内单张推理")
      console.log(taskValue.value)
      if (taskValue.value === "") {

      } else {
        let da = {}
        da.userId = JSON.parse(localStorage.getItem('userData')).userId
        quota.list(da).then(res => {
          if (res.code === 200) {
            console.log(res)
            if (res.data[0].quotaNum > 0) {
              console.log("开始推理")
              let ta = {}
              ta.taskId = taskValue.value
              inference.runTask(ta).then(res => {
                console.log(res)
                if (res.code === 200) {
                  ElMessage.success("运行成功")
                } else {
                  ElMessage.error("推理失败！")
                }
              })
            }
          } else {
            ElMessage.error("请求失败！")
          }
        })
      }
    }

    // 任务集单张推理
    function tasksImgInference() {
      console.log("任务集内单张推理")
    }

    // 单张照片单独推理
    const ImgInference = () => {
      console.log("单张推理")
      formRef.value.validate((valid) => {
        if(valid){
          formData.append("configs[]",JSON.parse(localStorage.getItem('userData')).userId.toString())
          formData.append("configs[]",exScriptsValue.value)
          formData.append("configs[]",backScriptsValue.value)
          formData.append("configs[]",modelsValue.value)

          console.log(formData)
          inference.runImg(formData).then(res => {
            console.log(res)
            if(res.code === 200){
              ElMessage.success("运行成功，请等待运行结果")
            }else{
              ElMessage.error("请求失败！")
            }
          })
        }
      })
    }

    // 加载文件
    function uploadFiles(event) {
      const files = event.target.files;

      for (let i = 0; i < files.length; i++) {
        const file = files[i]
        let id = Date.now() + i
        formData.append("files[]", file, id.toString());
        formData.append("names[]", file.name);
      }
    }

    // 拖拉加载文件
    const dropFiles = (event) => {
      event.preventDefault();
      const files = event.dataTransfer.files;
      dropFileName.value = ""

      for (let i = 0;i < files.length; i++){
        const file = files[i]
        let id = Date.now() + i
        formData.append("files[]", file, id.toString())
        formData.append("names[]", file.name)
        if(i === files.length-1){
          dropFileName.value += file.name
        }else{
          dropFileName.value += file.name+"、"
        }
      }
    }

    return {
      addVisible,
      addView,
      changeSelect,
      tasks,
      taskValue,
      tasksImg,
      tasksImgValue,
      ImgValue,
      Imgs,
      tasksInference,
      tasksImgInference,
      ImgInference,
      uploadFiles,
      exScriptsValue,
      exScripts,
      backScriptsValue,
      backScripts,
      modelsValue,
      models,
      formRef,
      imgData,
      dropFiles,
      dropFileName
    }
  }
}
</script>

<style scoped>
.drop_box{
  width: 300px;
  height: 200px;
  background-color: white;
  border-radius: 10px;
  border: 2px solid #d9d9d9;
  margin: auto auto auto -30px;
}
</style>